import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'home',
    component: () => import('../components/HomePage.vue')
  },
  {
    path: '/item/:id',
    name: 'item-detail',
    component: () => import('../components/ItemDetail.vue')
  },
  {
    path: '/publish',
    name: 'publish',
    component: () => import('../components/PublishItem.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/profile',
    name: 'profile',
    component: () => import('../components/Profile.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../components/LoginPage.vue')
  },

  {
    path: '/search',
    name: 'search',
    component: () => import('../components/SearchResults.vue')
  },
  
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 修复路由守卫
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 直接从本地存储检查登录状态
    const savedUser = localStorage.getItem('user')
    
    if (!savedUser) {
      // 未登录，重定向到登录页面
      next({
        name: 'login',
        query: { redirect: to.fullPath }
      })
    } else {
      // 已登录，继续导航
      next()
    }
  } else {
    // 不需要认证的路由，直接继续
    next()
  }
})

export default router